const {ipcMain} = require("electron");
const utf8 = require("utf8");
const SSHClient = require("ssh2").Client;

const serverInfo = require("./sshConfig");
const store = require("./sshDb");

const packMsg = (termName, msg) =>
  JSON.stringify({
    termName: termName,
    msg: msg
  })

function sshConn(win, connData) {
  console.log("createSocket")
  let obj = JSON.parse(connData)
  let sshInfo = {
    host: obj.host,
    port: obj.port,
    username: obj.uname,
    password: obj.passwd
  }
  store.set(obj.name, sshInfo)
  if (obj.isConn) {
    const ssh = new SSHClient();
    ssh.on("ready", function () {
      win.webContents.send("onTerminal", obj.termName, "*** SSH CONNECTION ESTABLISHED ***\r\n");
      console.log("*** SSH CONNECTION ESTABLISHED ***\r\n");
      ssh.shell({term: 'xterm'}, function (err, stream) {
        if (err) {
          return win.webContents.send("onTerminal", obj.termName, "\r\n*** SSH SHELL ERROR: " + err.message + " ***\r\n");
        }
        ipcMain.on("stdin", function (event, data) {
          console.log("ipcMain.on stdin");
          let obj = JSON.parse(data)
          if (obj.Op === "resize") {
            //console.log("client set cols, rows: ", obj.Cols, obj.Rows);
            stream.setWindow(obj.Rows, obj.Cols);
          } else if (obj.Op === "stdin") {
            //console.log("stdin: ", obj.Data);
            stream.write(obj.Data);
          }
        });
        stream.on("data", function (data) {
          win.webContents.send("onTerminal", obj.termName, data.toString('utf-8'));
          console.log("stream.on data win.webContents.send onTerminal", data.toString('utf-8'));
        }).on("close", function () {
          ssh.end();
        });
      });
    }).on("close", function () {
      //ws.close();
      console.log("close");
    }).on("error", function (err) {
      console.log("\r\n*** SSH CONNECTION ERROR: " + err.message + " ***\r\n");
      win.webContents.send("onTerminal", "\r\n*** SSH CONNECTION ERROR: " + err.message + " ***\r\n");
      //ws.close();
      console.log("close");
    }).connect(sshInfo);
  }
}

module.exports = sshConn;
